﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DoradoFramework.Core;
using Eflong.Tasks;

namespace Eflong.Tasks
{
    /// <summary>
    ///任务控制器
    /// </summary>
    public class TaskController : LazySingleton<TaskController>
    {
        private IList<ICustomTask> tasks = new List<ICustomTask>( );

        public TaskController( )
        {
            Assembly assembly = Assembly.GetAssembly( typeof( ICustomTask ) );
            foreach ( Type type in assembly.GetTypes( ) )
            {
                if ( type.GetInterface( "ICustomTask" ) != null && !type.IsAbstract )
                {
                    ICustomTask task = assembly.CreateInstance( type.ToString( ) , true ) as ICustomTask;
                    if ( task.Enabled )
                        tasks.Add( task );
                }
            }
        }

        /// <summary>
        /// 启动所有任务
        /// </summary>
        public void Start( )
        {
            foreach ( ICustomTask task in tasks )
            {
                task.Start( );
            }
        }

        /// <summary>
        /// 销毁所有任务
        /// </summary>
        public void Stop( )
        {
            foreach ( ICustomTask task in tasks )
            {
                task.Stop( );
            }
        }

        /// <summary>
        /// 重新启动所有的任务
        /// </summary>
        public void Restart( )
        {
            Stop( );
            Start( );
        }

        /// <summary>
        /// 启动指定的任务
        /// </summary>
        /// <param name="task"></param>
        public void Start( Type taskType )
        {
            ICustomTask targetTask = tasks.FirstOrDefault( n => n.GetType( ).FullName == taskType.FullName );
            if ( targetTask != null )
            {
                targetTask.Start( );
            }
        }

        /// <summary>
        /// 停止指定的任务
        /// </summary>
        /// <param name="task"></param>
        public void Stop( Type taskType )
        {
            ICustomTask targetTask = tasks.FirstOrDefault( n => n.GetType( ).FullName == taskType.FullName );
            if ( targetTask != null )
            {
                targetTask.Stop( );
            }
        }

        /// <summary>
        /// 重启指定的任务
        /// </summary>
        /// <param name="task"></param>
        public void Restart( Type taskType )
        {
            Stop( taskType );
            Start( taskType );
        }
    }
}